package com.weixin.util;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.io.FileUtils;

/**
 * 这个Https协议工具类，采用HttpsURLConnection实现。 提供get和post两种请求静态方法
 * 
 * @author marker
 * @date 2014年8月30日
 * @version 1.0
 */
public class HttpUtil {
    private static String BOUNDARY = "---------7d4a6d158c9";
    private static TrustManager myX509TrustManager = new X509TrustManager() {

	public void checkClientTrusted(X509Certificate[] arg0, String arg1)
		throws CertificateException {

	}
	public void checkServerTrusted(X509Certificate[] arg0, String arg1)
		throws CertificateException {

	}
	public X509Certificate[] getAcceptedIssuers() {
	    return null;
	}

    };

    public static String Httpspost(String url, String data) {
	System.out.println("请求url:" + url);
	try {
	    // 设置SSLContext
	    SSLContext sslcontext = SSLContext.getInstance("TLS");
	    sslcontext.init(null, new TrustManager[] { myX509TrustManager },
		    null);

	    // 打开连接
	    // 要发送的POST请求url?Key=Value&amp;Key2=Value2&amp;Key3=Value3的形式
	    URL requestUrl = new URL(url);
	    HttpsURLConnection httpsConn = (HttpsURLConnection) requestUrl
		    .openConnection();
	    // 设置套接工厂
	    httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());

	    // 加入数据
	    httpsConn.setRequestMethod("POST");
	    httpsConn.setDoOutput(true);
	    OutputStream out = httpsConn.getOutputStream();

	    if (data != null)
		out.write(data.getBytes("UTF-8"));
	    out.flush();
	    out.close();

	    // 获取输入流
	    BufferedReader in = new BufferedReader(new InputStreamReader(
		    httpsConn.getInputStream()));
	    int code = httpsConn.getResponseCode();
	    if (HttpsURLConnection.HTTP_OK == code) {
		StringBuffer response = new StringBuffer();
		String line;
		try {
		    while ((line = in.readLine()) != null)
			response.append(line + "\n");
		    in.close();
		} catch (IOException ioe) {
		    ioe.getStackTrace();
		}
		return response.toString();
	    }
	} catch (KeyManagementException e) {
	    e.printStackTrace();
	} catch (NoSuchAlgorithmException e) {
	    e.printStackTrace();
	} catch (MalformedURLException e) {
	    e.printStackTrace();
	} catch (ProtocolException e) {
	    e.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	}

	return null;
    }

    public static String Httpsget(String url) {
	System.out.println("getUrl" + url);
	try {
	    // 设置SSLContext
	    SSLContext sslcontext = SSLContext.getInstance("TLS");
	    sslcontext.init(null, new TrustManager[] { myX509TrustManager },
		    null);

	    // 打开连接
	    // 要发送的POST请求url?Key=Value&amp;Key2=Value2&amp;Key3=Value3的形式
	    URL requestUrl = new URL(url);
	    HttpsURLConnection httpsConn = (HttpsURLConnection) requestUrl
		    .openConnection();

	    // 设置套接工厂
	    httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());

	    // 加入数据
	    httpsConn.setRequestMethod("GET");
	    // httpsConn.setDoOutput(true);

	    // 获取输入流
	    BufferedReader in = new BufferedReader(new InputStreamReader(
		    httpsConn.getInputStream()));
	    int code = httpsConn.getResponseCode();
	    if (HttpsURLConnection.HTTP_OK == code) {
		StringBuffer response = new StringBuffer();
		String line;
		try {
		    while ((line = in.readLine()) != null)
			response.append(line + "\n");
		    in.close();
		} catch (IOException ioe) {
		    ioe.getStackTrace();
		}
		return response.toString();
	    }
	} catch (KeyManagementException e) {
	    e.printStackTrace();
	} catch (NoSuchAlgorithmException e) {
	    e.printStackTrace();
	} catch (MalformedURLException e) {
	    e.printStackTrace();
	} catch (ProtocolException e) {
	    e.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	}

	return null;
    }

    /**
     * 通过HTTP协议向指定的网络地址发送文件。
     * 
     * @param params
     *            传输过程中需要传送的参数
     * @param filename
     *            需要传送的文件在本地的位置。
     * @throws
     * @throws TransferException
     */
    public static String FileUpload(String url, File file) {
	System.out.println("post:"+url);
	if(!file.exists()){
	    return null;
	}
	HttpURLConnection conn = null; // URL连结对象。
	BufferedReader in = null; // 请求后的返回信息的读取对象。
	URL requesturl = null;
	try {
	    requesturl = new URL(url);
	    conn = (HttpURLConnection) requesturl.openConnection();
	    conn.setUseCaches(false);
	    conn.setDoOutput(true);
	    conn.setDoInput(true);
	    conn.setRequestMethod("POST");
	    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
	    
	    OutputStream out = new DataOutputStream(conn.getOutputStream());  
            byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线  
	    StringBuilder sb = new StringBuilder();    
            sb.append("--");    
            sb.append(BOUNDARY);    
            sb.append("\r\n");    
            sb.append("Content-Disposition: form-data;name=\"file\";filename=\""+ file.getName() + "\"\r\n");    
            sb.append("Content-Type:application/octet-stream\r\n\r\n");    
            System.out.println(sb);
            byte[] data = sb.toString().getBytes();  
            out.write(data);  
            DataInputStream datain = new DataInputStream(new FileInputStream(file));   
            int bytes = 0;  
            byte[] bufferOut = new byte[1024];  
            while ((bytes = datain.read(bufferOut)) != -1) {  
                out.write(bufferOut, 0, bytes);  
            }
            out.write(end_data);
            datain.close();
            out.flush();
	    out.close();
	    in = new BufferedReader(
		    new InputStreamReader(conn.getInputStream(),"UTF-8"));
	    // in.close();
	} catch (FileNotFoundException fe) {
	    InputStream err = ((HttpURLConnection) conn).getErrorStream();
	    if (err == null)
		in = new BufferedReader(new InputStreamReader(err));
	} catch (IOException ioe) {
	    ioe.printStackTrace();
	}

	// 返回提示信息
	StringBuffer response = new StringBuffer();
	String line;
	try {
	    while ((line = in.readLine()) != null)
		response.append(line+"\n");
	    in.close();
	} catch (IOException ioe) {
	    ioe.getStackTrace();
	}
	return response.toString();
    }
    public static File downLoadFile(String durl){
	System.out.println("download url:"+durl);
	HttpURLConnection conn = null;
	
	URL url=null;
	try {
	    url=new URL(durl);
	    conn=(HttpURLConnection) url.openConnection();
	    Map<String, List<String>> map= conn.getHeaderFields();
	    for (Entry<String, List<String>> h : map.entrySet()) {
		System.out.print("key:"+h.getKey());
		for (String s : h.getValue()) {
		    System.out.print("|"+s+",");
		}
		System.out.println();
	    }
	  String ss=  conn.getHeaderField("Content-disposition");
	  String aa=ss.substring(ss.indexOf("filename=\"")+10,ss.length()-1);
	  InputStream inputStream=conn.getInputStream();
	  File file=new File("D:/"+aa);
	  FileUtils.copyInputStreamToFile(inputStream, file);
	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	return null;
    }
}
